package com.tanhua.dubbo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询一位得分最高的推荐用户
     *
     * @param userId 用户id
     * @return 得分最高的用户对象
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 按照得分倒序
     *
     * @param userId 用户id
     * @param pageNum 第几页
     * @param pageSize 每页显示的条数
     * @return 自定义的PageInfo对象
     */
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        Criteria criteria = Criteria.where("toUserId").is(userId);
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(criteria).with(pageable);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<>(0, pageNum, pageSize, recommendUsers);
    }
}
